<template>
  <div class="flex flex-col h-full">
    <a-card>
      <template #title>
        <BaseTitle title="基础信息" />
      </template>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号"> {{ formState?.zydh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="出库仓库"> {{ formState?.ckckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="入库仓库">{{ formState?.rkckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="出库方式">{{ formState?.ckfstext || '-' }}</a-descriptions-item>
          <a-descriptions-item label="类别">{{ formState?.djlb === 0 ? '药材' : '物资' }}</a-descriptions-item>
          <a-descriptions-item label="制单人">{{ formState?.zdr || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单时间">{{ formState?.addtime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable
        :data-source="dataSource"
        column-code="00001068"
        :loading="loading"
        max-fill
        row-key="lsh"
        :extra-height="64"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'NO'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'mc'">
            <EditCell title="药品名称">
              <SelectMedicine
                :value="{ mc: record.mc, gg: record.gg, cj: record.cj }"
                type="移动"
                :search-params="{ ckbh: formState?.ckckbh, lx: 0 }"
                @select="onSelectMedicine($event, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'sl'">
            <EditCell title="转移数量">
              <BaseInput
                v-model:value="record.sl"
                v-input:int
                v-input-selection
                :auto-focus="focusCell === record.key"
                placeholder="请输入"
                @blur="editRow(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'cmemo'">
            <EditCell title="备注">
              <a-input v-model:value="record.cmemo" v-input-selection placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">删除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" type="primary" ghost @click="addRow()"> 新增明细 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import BaseTitle from '@/components/BaseTitle'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const focusCell = ref('')
const route = useRoute()
const router = useRouter()
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row, callBack) => {
  row.zydh = formState.value.zydh
  if (row.sl > parseInt(row.dqkc)) {
    row.sl = 0
    return message.error('移动数量不可大于库存量')
  }
  const { code, msg } = await post('/drugStorage/psiform/doSaveTransferFormDetail', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  callBack()
}

const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  if (newRow.length === 0) return message.error('没有新增的数据')
  for (const item of newRow) {
    if (item.ypbh && item.sl) {
      await new Promise((resolve) => {
        fetchSave(item, () => {
          resolve()
        })
      })
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  }
  // newRow.forEach((item) => {
  //   if (item.ypbh && item.sl) {
  //     fetchSave(item)
  //   } else {
  //     message.destroy()
  //     message.error('请填写完整信息')
  //   }
  // })
}
const onSelectMedicine = (medicine, row) => {
  row = Object.assign(row, medicine)
  row.ypbh = medicine?.ypbh
  row.nmiCode = medicine?.nmiCode
  row.cj = medicine?.cj
  row.sl = 1
  row.dj = medicine?.dj
  row.dqkc = medicine?.sl
  focusCell.value = row.key
  editRow(row)
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss') }
  dataSource.value.push(addRow)
}

const getMainData = async () => {
  const { data, code } = await post('/drugStorage/psiform/getTransferFormHeadList', {
    mcbm: route.query?.zydh
  })
  if (code === 0) {
    if (data[0].ckfs === 0) {
      data[0].ckfstext = '直接出库'
    } else if (data[0].ckfs === 1) {
      data[0].ckfstext = '申请单出库'
    } else if (data[0].ckfs === 2) {
      data[0].ckfstext = '调拨单出库'
    }
    formState.value = data[0]
  }
}

const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/drugStorage/psiform/getTransferFormDetailList', {
    zydh: route.query?.zydh
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
  }
}
const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/drugStorage/psiform/doDeleteTransferFormDetail', { lsh: row.lsh, dh: row.zydh })
    code === 0 ? getDetailData() : message.error(msg || '删除失败')
  }
}

watchEffect(() => {
  if (route.query?.zydh) {
    getMainData()
    getDetailData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
